package com.qt.myboot.service;

import com.qt.myboot.annotation.RedissonLock;
import com.qt.myboot.entity.User;
import com.qt.myboot.enums.LockType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description: redisson分布式锁 service类
 * @Author: xusl
 * @Date: 2019/6/12 20:14
 * @Param:
 * @return:
 **/
@Service
@Slf4j
public class RedissonLockService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

	@RedissonLock("'updateKey'")
	public void update(String key){
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			log.error("exp", e);
		}
	}

	@RedissonLock(value = "#user.id", waitTime = 3000)
	public void spel(User user){
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
            log.error("exp", e);
		}
	}

	@RedissonLock(value = "#user.id", lockType = LockType.WRITE_LOCK, waitTime = 10000)
	public void update(User user){
        Integer amount = Integer.parseInt(redisTemplate.opsForValue().get("productAmount"));
        if (0 < amount) {
            redisTemplate.opsForValue().set("productAmount", String.valueOf(amount - 1));
            log.info("write user : {}, 商品剩余数量: {}", user.getId(), amount -1);
        } else {
            log.info("换个姿势，再试一次吧~~");
        }
    }

	@RedissonLock(value = "#user.id", lockType = LockType.READ_LOCK, waitTime = 3000)
	public User read(User user) {
        log.info("read user : {}", user.getId());
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
            log.error("exp", e);
		}
		return user;
	}
}